<template>
  <a-modal v-model:open="aiOpen" title="AI生成的方案" :maskClosable="false" :width="800">
    <template v-if="planType == 'health'">
      <pre style="max-height: 500px; white-space: pre-wrap">{{ planData.content }}</pre>
    </template>
    <a-form
      ref="manaPlanFormRef"
      class="mana-plan-form"
      :label-col="{ style: { width: '80px' } }"
      disabled
    >
      <template v-if="planType == 'diet'">
        <div>
          <!-- <div class="season-row">
            <span
              :class="['season-item', secindex === seasonKey ? 'season-item-active' : '']"
              v-for="(seasonItem, secindex) in planData.seasons"
              :key="secindex"
              @click="seasonChange(secindex)"
            >
              {{ seasonLabel[seasonItem.season] }}
            </span>
          </div> -->

          <div class="week-row" v-if="planData.seasons && planData.seasons.length">
            <div v-for="(weekItem, weekIndex) in planData.seasons[seasonKey].week" :key="weekIndex">
              <span
                @click="weekChange(weekIndex)"
                :class="['week-item', weekIndex === activeKey ? 'week-item-active' : '']"
              >
                第{{ weekDay[weekItem.day - 1] }}天
              </span>
              <a-divider
                style="margin-right: 13px"
                v-if="weekIndex !== planData.seasons[seasonKey].week.length - 1"
                type="vertical"
              />
            </div>
          </div>
          <div>
            <p class="diet-info-box">
              食谱详情：
              <span class="diet-info diet-all">
                总摄入
                <span :class="['diet-all', getFoodInfoStatus('energy')]">
                  {{ getFoodInfo('energy') }}
                </span>
                /推荐{{ numberToFixedEnergy(recommendEnergy) }}千卡
              </span>
              <span class="diet-info">
                碳水
                <span :class="[getFoodInfoStatus('cho')]">{{ getFoodInfo('cho') }}</span>
                /推荐{{ numberToFixed(recommendCho) }}g
              </span>
              <span class="diet-info">
                蛋白质
                <span :class="[getFoodInfoStatus('pro')]">{{ getFoodInfo('pro') }}</span>
                /推荐{{ numberToFixed(recommendPro) }}g
              </span>
              <span class="diet-info">
                脂肪
                <span :class="[getFoodInfoStatus('fat')]">{{ getFoodInfo('fat') }}</span>
                /推荐{{ numberToFixed(recommendFat) }}g
              </span>
            </p>

            <a-form-item label="早餐" :labelCol="{ style: { width: '70px' } }" required>
              <div class="dict-group">
                <template
                  v-if="
                    planData.seasons && planData.seasons.length && planData.seasons[seasonKey].week
                  "
                >
                  <div
                    class="dict-name"
                    v-for="(diet, dietIndex) in planData.seasons[seasonKey].week[activeKey]
                      .itemContent.breakfast.food_items"
                    :key="dietIndex"
                  >
                    <template v-if="diet.ingredients">
                      <span>
                        <!--  -->
                        <span
                          class="food-sub-name"
                          v-for="(subDiet, subDietIndex) in diet.ingredients"
                          :key="subDietIndex"
                        >
                          {{ subDiet.name }}
                          （
                          <span class="food-weight">
                            {{ (Number(subDiet.amount) * (subDiet.ratio || 1)).toFixed(0) }}
                          </span>
                          g）
                        </span>
                      </span>
                    </template>
                  </div>
                </template>
              </div>
            </a-form-item>

            <a-form-item label="早加餐" :labelCol="{ style: { width: '70px' } }">
              <div class="dict-group">
                <template
                  v-if="
                    planData.seasons && planData.seasons.length && planData.seasons[seasonKey].week
                  "
                >
                  <div
                    class="dict-name"
                    v-for="(diet, dietIndex) in planData.seasons[seasonKey].week[activeKey]
                      .itemContent.breakfast_plus.food_items"
                    :key="dietIndex"
                  >
                    <template v-if="diet.ingredients">
                      <span>
                        <span
                          class="food-sub-name"
                          v-for="(subDiet, subDietIndex) in diet.ingredients"
                          :key="subDietIndex"
                        >
                          {{ subDiet.name }}
                          （
                          <span class="food-weight">
                            {{ (Number(subDiet.amount) * (subDiet.ratio || 1)).toFixed(0) }}
                          </span>
                          g）
                        </span>
                      </span>
                    </template>
                  </div>
                </template>
              </div>
            </a-form-item>

            <a-form-item label="午餐" :labelCol="{ style: { width: '70px' } }" required>
              <div class="dict-group">
                <template
                  v-if="
                    planData.seasons && planData.seasons.length && planData.seasons[seasonKey].week
                  "
                >
                  <div
                    class="dict-name"
                    v-for="(diet, dietIndex) in planData.seasons[seasonKey].week[activeKey]
                      .itemContent.lunch.food_items"
                    :key="dietIndex"
                  >
                    <template v-if="diet.ingredients">
                      <span>
                        <span
                          class="food-sub-name"
                          v-for="(subDiet, subDietIndex) in diet.ingredients"
                          :key="subDietIndex"
                        >
                          {{ subDiet.name }}
                          （
                          <span class="food-weight">
                            {{ (Number(subDiet.amount) * (subDiet.ratio || 1)).toFixed(0) }}
                          </span>
                          g）
                        </span>
                      </span>
                    </template>
                  </div>
                </template>
              </div>
            </a-form-item>

            <a-form-item label="午加餐" :labelCol="{ style: { width: '70px' } }">
              <div class="dict-group">
                <template
                  v-if="
                    planData.seasons && planData.seasons.length && planData.seasons[seasonKey].week
                  "
                >
                  <div
                    class="dict-name"
                    v-for="(diet, dietIndex) in planData.seasons[seasonKey].week[activeKey]
                      .itemContent.lunch_plus.food_items"
                    :key="dietIndex"
                  >
                    <template v-if="diet.ingredients">
                      <span>
                        <span
                          class="food-sub-name"
                          v-for="(subDiet, subDietIndex) in diet.ingredients"
                          :key="subDietIndex"
                        >
                          {{ subDiet.name }}
                          （
                          <span class="food-weight">
                            {{ (Number(subDiet.amount) * (subDiet.ratio || 1)).toFixed(0) }}
                          </span>
                          g）
                        </span>
                      </span>
                    </template>
                  </div>
                </template>
              </div>
            </a-form-item>

            <a-form-item label="晚餐" :labelCol="{ style: { width: '70px' } }" required>
              <div class="dict-group">
                <template
                  v-if="
                    planData.seasons && planData.seasons.length && planData.seasons[seasonKey].week
                  "
                >
                  <div
                    class="dict-name"
                    v-for="(diet, dietIndex) in planData.seasons[seasonKey].week[activeKey]
                      .itemContent.dinner.food_items"
                    :key="dietIndex"
                  >
                    <template v-if="diet.ingredients">
                      <span>
                        <span
                          class="food-sub-name"
                          v-for="(subDiet, subDietIndex) in diet.ingredients"
                          :key="subDietIndex"
                        >
                          {{ subDiet.name }}
                          （
                          <span class="food-weight">
                            {{ (Number(subDiet.amount) * (subDiet.ratio || 1)).toFixed(0) }}
                          </span>
                          g）
                        </span>
                      </span>
                    </template>
                  </div>
                </template>
              </div>
            </a-form-item>

            <a-form-item label="晚加餐" :labelCol="{ style: { width: '70px' } }">
              <div class="dict-group">
                <template
                  v-if="
                    planData.seasons && planData.seasons.length && planData.seasons[seasonKey].week
                  "
                >
                  <div
                    class="dict-name"
                    v-for="(diet, dietIndex) in planData.seasons[seasonKey].week[activeKey]
                      .itemContent.dinner_plus.food_items"
                    :key="dietIndex"
                  >
                    <template v-if="diet.ingredients">
                      <span>
                        <span
                          class="food-sub-name"
                          v-for="(subDiet, subDietIndex) in diet.ingredients"
                          :key="subDietIndex"
                        >
                          {{ subDiet.name }}
                          （
                          <span class="food-weight">
                            {{ (Number(subDiet.amount) * (subDiet.ratio || 1)).toFixed(0) }}
                          </span>
                          g）
                        </span>
                      </span>
                    </template>
                  </div>
                </template>
              </div>
            </a-form-item>
          </div>
        </div>
      </template>
      <template v-if="planType == 'sports'">
        <div class="sprot-form">
          <a-tabs v-model:activeKey="sportWeekIndex">
            <a-tab-pane
              :tab="`第${weekDay[child.day - 1]}天`"
              v-for="(child, childIndex) in planData.week"
              :key="childIndex"
            >
              <a-form-item label="运动类型" required>
                <a-radio-group :options="sportTypeData" v-model:value="child.sportType" />
              </a-form-item>
              <template v-if="child.sportType != '3'">
                <a-form-item label="有氧运动" required v-if="child.sportType == '1'">
                  <a-select
                    v-model:value="child.aerobicSport.sportName"
                    showSearch
                    :options="aerobicData"
                    placeholder="请选择运动"
                    :listHeight="200"
                  />
                  <a-form-item-rest>
                    <a-input-number
                      v-model:value="child.aerobicSport.total"
                      style="width: 150px; margin: 0 8px"
                      step="1"
                      min="1"
                      :precision="0"
                      addon-after="分钟"
                    />
                  </a-form-item-rest>
                </a-form-item>
                <a-form-item label="抗阻动作" required v-if="child.sportType == '2'">
                  <div class="sport-group">
                    <div
                      class="sport-name"
                      v-for="(sport, sportIndex) in child.resistanceSports"
                      :key="sportIndex"
                    >
                      <span>
                        {{ sport.sportName }}，
                        <span class="sport-time">
                          每组
                          {{ sport.total }}
                          次
                        </span>
                      </span>
                    </div>
                  </div>
                </a-form-item>
                <a-form-item label="动作组数" required v-if="child.sportType == '2'">
                  <a-input-number
                    v-model:value="child.groupNum"
                    step="1"
                    min="1"
                    :precision="0"
                    addonAfter="组"
                  />
                </a-form-item>
                <a-form-item label="热身运动" required>
                  <div class="sport-group">
                    <div
                      class="sport-name"
                      v-for="(sport, sportIndex) in child.warmupSports"
                      :key="sportIndex"
                    >
                      <span>
                        {{ sport.sportName }}，
                        <span class="sport-time">
                          {{ sport.total }}
                          次
                        </span>
                      </span>
                    </div>
                  </div>
                </a-form-item>
                <a-form-item label="拉伸运动" required>
                  <div class="sport-group">
                    <div
                      class="sport-name"
                      v-for="(sport, sportIndex) in child.stretchSports"
                      :key="sportIndex"
                    >
                      <span>
                        {{ sport.sportName }}，
                        <span class="sport-time">
                          {{ sport.total }}
                          s
                        </span>
                      </span>
                    </div>
                  </div>
                </a-form-item>
              </template>
            </a-tab-pane>
          </a-tabs>
        </div>
      </template>
    </a-form>
    <template #footer>
      <a-button @click="aiOpen = false">关闭</a-button>
      <a-button type="primary" @click="useAiPlan">确认使用</a-button>
    </template>
  </a-modal>
</template>
<script lang="ts" setup>
import store from '@/store'
import { ref, reactive, onMounted } from 'vue'
const aiOpen = ref(false)
const planData = ref()
const planType = ref()
const emit = defineEmits(['setPlan'])

const sportWeekIndex = ref(0)
const weekDay = reactive<any>(['一', '二', '三', '四', '五', '六', '七'])
const sportTypeData = reactive([
  { label: '有氧', value: '1' },
  { label: '抗阻', value: '2' },
  { label: '休息日', value: '3' }
])
const sportDictData = ref()
const aerobicData = ref([]) // 有氧运动数据

const seasonLabel = reactive<any>({
  spring: '春季',
  summer: '夏季',
  fall: '秋季',
  winter: '冬季'
})
const seasonKey = ref(0)
const activeKey = ref(0)

const recommendEnergy = ref<number>(0)
const recommendCho = ref<number>(0)
const recommendPro = ref<number>(0)
const recommendFat = ref<number>(0)

const numberToFixed = (num: any) => {
  if (num == undefined) {
    return '--'
  } else {
    return Number(num).toFixed(1)
  }
}

const numberToFixedEnergy = (num: any) => {
  if (num == undefined) {
    return '--'
  } else {
    return Number(num).toFixed(0)
  }
}

// 四季切换
const seasonChange = (index: any) => {
  seasonKey.value = index
  activeKey.value = 0
}

// 星期切换
const weekChange = (index: any) => {
  activeKey.value = index
}

const init = (data: any, type: string, extra?: any) => {
  aiOpen.value = true
  planType.value = type
  planData.value = data

  if (type == 'sports') {
    sportDictData.value = store.userApp.sportDictList.map((vo: any) => {
      return {
        ...vo,
        label: vo.sportName,
        value: vo.sportName
      }
    })

    aerobicData.value = sportDictData.value.filter((item) => {
      return item.isAerobic
    })
    sportWeekIndex.value = 0
  } else if (type == 'diet') {
    recommendEnergy.value = extra.energy
    recommendCho.value = extra.cho
    recommendPro.value = extra.pro
    recommendFat.value = extra.fat

    seasonKey.value = 0
    activeKey.value = 0
  }
}

// 能量统计
const getFoodInfo = (type: any) => {
  if (
    planData.value &&
    planData.value.seasons &&
    planData.value.seasons.length &&
    planData.value.seasons[seasonKey.value].week &&
    planData.value.seasons[seasonKey.value].week.length
  ) {
    const data: any = planData.value.seasons[seasonKey.value].week[activeKey.value].itemContent
    let total: any = 0
    data.breakfast.food_items.forEach((item) => {
      item.ingredients.forEach((child) => {
        if (child[type]) {
          total += foodTypeMash(child, type)
        }
      })
    })

    data.lunch.food_items.forEach((item) => {
      item.ingredients.forEach((child) => {
        if (child[type]) {
          total += foodTypeMash(child, type)
        }
      })
    })

    data.dinner.food_items.forEach((item) => {
      item.ingredients.forEach((child) => {
        if (child[type]) {
          total += foodTypeMash(child, type)
        }
      })
    })

    if (data.breakfast_plus) {
      data.breakfast_plus.food_items.forEach((item) => {
        item.ingredients.forEach((child) => {
          if (child[type]) {
            total += foodTypeMash(child, type)
          }
        })
      })
    }

    if (data.lunch_plus) {
      data.lunch_plus.food_items.forEach((item) => {
        item.ingredients.forEach((child) => {
          if (child[type]) {
            total += foodTypeMash(child, type)
          }
        })
      })
    }

    if (data.dinner_plus) {
      data.dinner_plus.food_items.forEach((item) => {
        item.ingredients.forEach((child) => {
          if (child[type]) {
            total += foodTypeMash(child, type)
          }
        })
      })
    }

    if (type == 'energy') {
      return total ? total.toFixed(0) : '--'
    } else {
      return total ? total.toFixed(1) : '--'
    }
  } else {
    return '--'
  }
}

const foodTypeMash = (child: any, type: any) => {
  const value = (Number(child[type]) / 100) * Number(child.amount) * (child.ratio || 1)
  if (type == 'energy') {
    return Number(value.toFixed(0))
  } else {
    return Number(value.toFixed(1))
  }
}

// 浮动值 状态
const getFoodInfoStatus = (type: any) => {
  switch (type) {
    case 'energy':
      return recommendEnergy.value
        ? matchClassName(recommendEnergy.value, getFoodInfo('energy'))
        : ''
    case 'cho':
      return recommendCho.value ? matchClassName(recommendCho.value, getFoodInfo('cho')) : ''
    case 'pro':
      return recommendPro.value ? matchClassName(recommendPro.value, getFoodInfo('pro')) : ''
    case 'fat':
      return recommendFat.value ? matchClassName(recommendFat.value, getFoodInfo('fat')) : ''
    default:
      return ''
  }
}

const matchClassName = (base: number, value: number) => {
  const floatPercent = ((value - base) / base) * 100
  const absFloatPercent = Math.abs(floatPercent)

  if (absFloatPercent <= 5) {
    return 'diet-num-normal'
  } else if (absFloatPercent <= 10) {
    return 'diet-num-warn'
  } else if (absFloatPercent > 10) {
    return 'diet-num-danger'
  } else {
    return ''
  }
}

const useAiPlan = () => {
  aiOpen.value = false
  emit('setPlan', planData.value)
}

defineExpose({
  init
})
</script>
<style lang="less" scoped>
.mana-plan-form .ant-form-item {
  margin-bottom: 12px;
}

.mana-plan-form .sprot-form .ant-form-item {
  margin-bottom: 18px;
}

.mana-plan-form .sprot-form {
  .ant-form-item {
    margin-bottom: 18px;
  }
}

.sport-group {
  min-height: 42px;
  padding: 0 4px;
}

.sport-name {
  display: inline-block;
  padding: 5px 8px;
  margin: 4px;
  color: #1d2129;
  background: #f2f3f5;
  border-radius: 2px;
}

.dict-group {
  min-height: 42px;
  padding: 0 4px;
}

.dict-name {
  display: inline-block;
  padding: 5px 8px;
  margin: 4px;
  color: #1d2129;
  background: #f2f3f5;
  border-radius: 2px;
}

.food-sub-name {
  font-size: 14px;
  color: #1d2129;
}

.food-weight {
  color: #165dff;
  cursor: pointer;
}

.dict-del-icon {
  margin-left: 4px;
  font-size: 12px;
  color: #4e5969;
  cursor: pointer;
}

.dict-btn {
  display: inline-block;
  padding: 5px 8px;
  margin: 4px;
  color: #165dff;
  cursor: pointer;
  background: #e8f3ff;
}

.season-row {
  margin-bottom: 12px;
}

.season-item {
  padding: 5px 16px;
  margin-right: 16px;
  font-size: 14px;
  color: #4e5969;
  cursor: pointer;
  background: #f7f8fa;
  border-radius: 100px;
}

.season-item-active {
  color: #165dff;
  background: #e8f3ff;
}

.week-row {
  display: flex;
  margin-bottom: 12px;
}

.week-item {
  color: #4e5969;
  cursor: pointer;
}

.week-item-active {
  color: #165dff;
}

.diet-info-box {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.diet-info {
  margin-right: 12px;
  font-size: 14px;
  font-weight: 400;
  color: #4e5969;
}

.diet-all {
  font-size: 14px;
  font-weight: 500;
  color: #1d2129;
}

.diet-num-normal {
  color: #00b42a;
}

.diet-num-warn {
  color: #ff7d00;
}

.diet-num-danger {
  color: #f53f3f;
}
</style>
